package com.leige.tesseractocrlibrary

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build

/**
 * Created by liulei
 * 2019/12/24 9:29
 * Tesseract初始化,封装给上层使用的
 */
class TesseractInitHelper {

    class Config {
        var traineddataPath: String = ""
        var traineddatafileName = ""
        var trainedLang: String = ""

        constructor()
        constructor(traineddataPath: String, traineddatafileName: String, trainedLang: String) {
            this.traineddataPath = traineddataPath
            this.traineddatafileName = traineddatafileName
            this.trainedLang = trainedLang
        }
    }

    private val defaultConfig = Config(
        "/storage/emulated/0/Download/chi_sim.traineddata",
        "chi_sim.traineddata",
        "chi_sim"
    )

    private var config: Config = defaultConfig

    fun initConfig(setConfig: Config) {
        this.config = setConfig
    }

    private var ocr: TesseractOCR? = null

    fun init(context: Context) {

        val hasWriteFilePermisson = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val permission =
                context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            permission == PackageManager.PERMISSION_GRANTED
        } else true

        if (!hasWriteFilePermisson) {
            throw IllegalArgumentException("new write sd permission..")
        }

        try {
            if (ocr != null) {
                ocr?.onDestroy()
            }
        } catch (ex: Throwable) {
            ex.printStackTrace()
        }
        ocr = TesseractOCR(context)
        ocr?.initDataConfig(config.traineddatafileName, config.traineddataPath, config.trainedLang)
        ocr?.initApi()
    }

    fun getOCRResult(bitmap: Bitmap): String? {
        return ocr?.getOCRResult(bitmap)
    }

    fun setOnlySupportDigital() {
        ocr?.setOnlySupportDigital()
    }

    /**
     * release之后可以调用init再次使用
     */
    fun release() {
        try {
            ocr?.onDestroy()
            ocr = null
        } catch (ex: Throwable) {
            ex.printStackTrace()
        }
    }
}